<?php

namespace app\controller\wmapi\approvalsetting;

use app\controller\wmapi\IndexController;
use app\controller\wmapi\order\OrderController;
use app\controller\wmapi\PublicCommentController;
use app\model\WaApproveSetting;
use app\model\WaChannel;
use app\model\WaOrders;
use app\model\WaOrdersPurchase;
use app\model\WaPayrollRequisitionExamineApprove;
use app\model\WaPayrollRequisitionExamineApproveFlow;
use app\model\WaPurchasePayrollRequisition;
use app\model\WaSalesOrdersExamineApprove;
use app\model\WaSalesOrdersExamineApproveFlow;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaPurchaseOrdersExamineApprove;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;
use function GuzzleHttp\json_encode;
use function Symfony\Component\VarDumper\Cloner\__isset;

class ApproveSettingController extends Validate
{
    /**
     * 审批流配置按人
     * @param Request $request
     * @return \support\Response
     */
    public function approveSetting(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (!$param['approve_flow']) {
            return IndexController::errored('', '参数有误');
        }
        // 是否有设置流程
        $status = 0;
        if ($param['approve_flow']) {
            $status = 1;
        }
        $approve_flow_all = $param['approve_flow'];
        IndexController::logSuccessed('approveSetting', $approve_flow_all, $adminId);
        // 由哪个部门发起审批的审批流流程

        $array_all = [];
        $ii = 0; // 最外层的sort
        foreach ($approve_flow_all as $kall) { // 审批流最外层
            $counts = count($kall['approve_flow_by_initiator']);
            $i = 0; // 最外层的sort 轮到那一层审批的sort
            $ary = [];
            $kall['sort'] = $ii++;
            $approve_flow_by_initiator = $kall['approve_flow_by_initiator'];
            foreach ($approve_flow_by_initiator as $k) { // 每个人或部门的审批流

                $i++;
//                $sort_data = [
//                    'sort' => 'sort'.$i,
//                    'approve_admin_id' => $k['approve_admin_id']
//                ];
                $k['sort'] = 'sort' . $i;

//                array_push($ary, $k['approve_flow'][$ii]['approve_admin_id']);
//                    $k['ary'] = $sort_data;

                // 为什么两个循环要分开  因为上一步是创建 sort 标识  这一步是要记录上一级 和下一级的标识
                if ($i == 1) {
//                        $sort_data['superior_sort'] = 0;
                    $k['superior_sort'] = 0;
                } else {
//                        $sort_data['superior_sort'] = 'sort' . ($i-1);
                    $k['superior_sort'] = 'sort' . ($i - 1);
                }

                if ($i == $counts) {
//                        $sort_data['next_sort'] = 0;
                    $k['next_sort'] = 0;
                } else {
                    if ($i == $counts) {
                        $i = 0;
                    }
//                        $sort_data['next_sort'] = 'sort' . ($i+1);
                    $k['next_sort'] = 'sort' . ($i + 1);
                }
                array_push($ary, $k);
            }
            $kall['approve_flow_by_initiator'] = $ary;
            array_push($array_all, $kall);
        }


        $data = [
            'approve_flow' => $array_all,
            'updated_at' => dateTime(),
            'status' => $status, // 0 未设置 1 已设置
        ];
//        return IndexController::successed(json_encode($data), '审批流配置成功');


        \support\Db::beginTransaction();
        try{
            $condition = ['id' => $param['approve_id']];
            $res = WaApproveSetting::updated($condition, $data);
            if (!$res) {
                return IndexController::errored($res, '审批流配置失败');
            } else {
                return IndexController::successed($res, '审批流配置成功');
            }
        } catch (\Throwable $exception) {
            IndexController::logError('approveSetting', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '审批流配置按人更新失败');
        }


    }

    /**
     * 审批流列表不分页
     * @param Request $request
     * @return mixed
     */
    public function approveListAll(Request $request)
    {
        $param = $request->all();

        $res = WaApproveSetting::all();

        return IndexController::successed($res, '审批流列表');
    }

    /**
     * 审批流详情
     * @param Request $request
     * @return mixed
     */
    public function approveFlowDetail(Request $request)
    {
        $param = $request->all();
        $res = WaApproveSetting::find(['id' => $param['approve_id']]);

        return IndexController::successed($res, '审批流列表');
    }


    /**
     * 当前部门的审批流-人
     * @return string
     */
    public static function flowSttingBySort($setting, $sort)
    {
        // 采购订单审流 查询
        // 1供应商审批 2销售订单审批 3销售合同审批 4采购订单审批 5采购合同审批 6采购请款审批 7交强险请款审批
        $find = WaApproveSetting::find(['id' => $setting]);
        $find = json_decode($find);
        // 获取当前用户对应部门所设置的审批流设置
        $flow = '';
        if ($find) {
//            $find->approve_flow = json_decode($find->approve_flow);
            foreach ($find->approve_flow as $kf) {
                if ($sort) {
                    if (intval($kf->sort) == intval($sort)) {
                        $flow = $kf->approve_flow_by_initiator;
                    }
                } else {
                    if (intval($kf->sort) == 0) {
                        $flow = $kf->approve_flow_by_initiator;
                    }
                }

            }
        }

        return $flow;
    }

    /**
     * 抄送人 - 前 获取
     * @param $setting
     * @param $sort
     * @return string
     */
    public static function flowSttingBySendBefore($setting, $sort)
    {
        // 采购订单审流 查询
        // 1供应商审批 2销售订单审批 3销售合同审批 4采购订单审批 5采购合同审批 6采购请款审批 7交强险请款审批
        $find = WaApproveSetting::find(['id' => $setting]);
        $find = json_decode($find);
        // 获取当前用户对应部门所设置的审批流设置
        $flow = '';
        $admin_ids = [];
        if ($find) {
//            $find->approve_flow = json_decode($find->approve_flow);
            foreach ($find->approve_flow as $kf) {
                if ($sort){
                    if (intval($kf->sort) == intval($sort)) {
//                        $admin_ids = $kf->send_before;
                        if (property_exists($kf, 'send_before')) {
                            $admin_ids = $kf->send_before;
                        }
                    }
                } else {
                    if (intval($kf->sort) == 0) {
//                        $admin_ids = $kf->send_before;
                        if (property_exists($kf, 'send_before')) {
                            $admin_ids = $kf->send_before;
                        }
                    }
                }

            }
        }

        return $admin_ids;
    }

    /**
     * 抄送人 - 后 获取
     * @param $setting
     * @param $sort
     * @return string
     */
    public static function flowSttingBySendAfter($setting, $sort)
    {
        // 采购订单审流 查询
        // 1供应商审批 2销售订单审批 3销售合同审批 4采购订单审批 5采购合同审批 6采购请款审批 7交强险请款审批
        $find = WaApproveSetting::find(['id' => $setting]);
        $find = json_decode($find);
        // 获取当前用户对应部门所设置的审批流设置
        $flow = '';
        if ($find) {
//            $find->approve_flow = json_decode($find->approve_flow);
            foreach ($find->approve_flow as $kf) {
                if ($sort) {
                    if (intval($kf->sort) == intval($sort)) {
                        $admin_ids = $kf->send_after;

                    }
                } else {
                    if (intval($kf->sort) == 0) {
                        $admin_ids = $kf->send_after;
                    }
                }

            }
        }

        return $admin_ids;
    }


    // 创建请款审批流 - 采购订单 （定金 尾款）
    public static function payrollApproveAdd($adminId, $total_price, $param, $purchase_payroll_sn, $purchase_order_sn)
    {
//            if (round($param['total_price'], 2) < (round($param['requested_price'], 2) + round($param['this_request_price'], 2))) {
        // 本次请款金额超出总金额 需要审批

        // 获取当前用户对应部门所设置的审批流设置
//        $flow = ApproveSettingController::flowStting(2, $department_id);
        if (array_key_exists('flow', $param)) {
            $flow = $param['flow'];
            $admin_ids = json_encode($flow[0]['approve_admin_id']);

//            可以把抄送人加到消息通知组里一起发送，但是有个问题抄送人不一定有权限看  所以 需要要个单独的 抄送消息 具体要通知什么消息

        } else {
            if (array_key_exists('sort', $param)) {
                if ($param['sort']) {
                    $sort = $param['sort'];
                } else {
                    $sort = 0;
                }
            } else {
                $sort = 0;
            }
            $flow = ApproveSettingController::flowSttingBySort(6, $sort);// sort默认选第一个
        }
        $send_before = [];
        $send_after = [];
        if (array_key_exists('send_before', $param)) {
            if ($param['send_before']) {
                $send_before = $param['send_before'];
            }
        }

        if (array_key_exists('send_after', $param)) {
            if ($param['send_after']) {
                $send_after = $param['send_after'];
            }
        }
        \support\Db::beginTransaction();
        try {
            // 创建采购请款审批:
            // 创建新的采购请款单审批 -> 创建采购请款单审批流第一条待审核记录
            // 判断 采购请款单的状态 是否符合创建审核条件 是否同一笔审批未结束 采购请款单审批状态 0 审批中 1 通过 2 驳回 3作废 4删除
            $checkPurchaseApprove = WaPayrollRequisitionExamineApprove::find($adminId, ['purchase_payroll_sn' => $purchase_payroll_sn]);
            $checkPurchaseApprove = json_decode($checkPurchaseApprove);
            if ($checkPurchaseApprove) {
                if ($checkPurchaseApprove->status == 0 || $checkPurchaseApprove->status == 1) {
                    return '该订单在审核流程中不能重复创建';
                }
            }

            $pr_no = 'PR' . IndexController::getRandomNum(6);

            $approve_data = [
                'pr_no' => $pr_no, // 采购请款单编号
                'total_amount' => $total_price, // 订单金额
                'requested_price' => round($total_price, 2), //已请款金额
                'this_request_price' => round($total_price, 2), //本次请款金额
                'price_name' => $param['price_name'], // 请款项目名称
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'status' => 0, // 状态 0 审批中 1 通过 2 驳回
                'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
                'approve_flow' => json_encode($flow), // 当前采购请款单的审批流流程
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'initiator_admin_id' => $adminId->id, //
                'purchase_payroll_sn' => $purchase_payroll_sn, // 采购请款单编号
                'purchase_order_sn' => $purchase_order_sn, // 采购单编号
            ];

            if ($send_before) {
                $approve_data['approve_flow_send_before'] = json_encode($send_before);
            }
            if ($send_after) {
                $approve_data['approve_flow_send_after'] = json_encode($send_after);
            }
            $add_PurchaseEa = WaPayrollRequisitionExamineApprove::create($approve_data); // 创建的审批id
            if (!$add_PurchaseEa) {
                return '创建采购请款单审批驳回';
            }

            // 创建审批流 1供应商审批 2销售订单审批 3销售合同审批 4采购请款单审批 5采购合同审批 6采购请款审批 7交强险请款审批
//            // 采购请款单审流 创建 (创建审批流中的第一个审批)
            $approve_log_data = [
                'pr_no' => $pr_no, // 采购请款单编号
                'check_id' => $add_PurchaseEa, // 审核id
                'admin_ids' => json_encode($flow[0]['approve_admin_id']), //
                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'status' => 0, //待审核 1审批通过 2 审批驳回  4  删除
                'price_name' => $param['price_name'], // 请款项目名称
                'purchase_payroll_sn' => $purchase_payroll_sn, // 采购请款单编号
            ];

            $res = WaPayrollRequisitionExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                return '创建采购请款单审批流失败';
            }
            $up_payroll = WaPurchasePayrollRequisition::updated(['status' => 1, 'pr_no' => $pr_no, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $purchase_payroll_sn]);
            if (!$up_payroll) {
                return '请款单状态修改失败';
            }
            return 'true';

        } catch (\Throwable $exception) {

            IndexController::logError('payrollApproveAdd-static', $param, $adminId, $exception);
            \support\Db::rollBack();
            return 'false';
        }


    }

    // 创建请款审批流 - 车务
    public static function payrollApproveAddByVin($adminId, $total_price, $param, $purchase_payroll_sn, $purchase_order_sn, $vin)
    {
//            if (round($param['total_price'], 2) < (round($param['requested_price'], 2) + round($param['this_request_price'], 2))) {
        // 获取当前用户对应部门所设置的审批流设置
//        $flow = ApproveSettingController::flowStting(2, $department_id);
        if (array_key_exists('flow', $param)) {
            $flow = $param['flow'];
            $admin_ids = json_encode($flow[0]['approve_admin_id']);

//            可以把抄送人加到消息通知组里一起发送，但是有个问题抄送人不一定有权限看  所以 需要要个单独的 抄送消息 具体要通知什么消息

        } else {
            if (array_key_exists('sort', $param)) {
                if ($param['sort']) {
                    $sort = $param['sort'];
                } else {
                    $sort = 0;
                }
            } else {
                $sort = 0;
            }
            $flow = ApproveSettingController::flowSttingBySort(6, $sort);// sort默认选第一个
        }
        $send_before = [];
        $send_after = [];
        if (array_key_exists('send_before', $param)) {
            if ($param['send_before']) {
                $send_before = $param['send_before'];
            }
        }

        if (array_key_exists('send_after', $param)) {
            if ($param['send_after']) {
                $send_after = $param['send_after'];
            }
        }


        \support\Db::beginTransaction();
        try{
// 创建采购请款审批:
            // 创建新的采购请款单审批 -> 创建采购请款单审批流第一条待审核记录
            // 判断 采购请款单的状态 是否符合创建审核条件 是否同一笔审批未结束 采购请款单审批状态 0 审批中 1 通过 2 驳回 3作废 4删除
            $checkPurchaseApprove = WaPayrollRequisitionExamineApprove::find($adminId, ['purchase_payroll_sn' => $purchase_payroll_sn]);
            $checkPurchaseApprove = json_decode($checkPurchaseApprove);
            if ($checkPurchaseApprove) {
                if ($checkPurchaseApprove->status == 0 || $checkPurchaseApprove->status == 1) {
                    return '该订单在审核流程中不能重复创建';
                }
            }

            $pr_no = 'PR' . IndexController::getRandomNum(6);

            $approve_data = [
                'pr_no' => $pr_no, // 采购请款单编号
                'total_amount' => $total_price, // 订单金额
                'requested_price' => round($total_price, 2), //已请款金额
                'this_request_price' => round($total_price, 2), //本次请款金额
                'price_name' => $param['price_name'], // 请款项目名称
                'admin_id' => $adminId->id, // 创建人id(提交订单审批的创建人)
                'admin_name' => $adminId->nickname, // 创建人名称
                'status' => 0, // 状态 0 审批中 1 通过 2 驳回
                'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
                'approve_flow' => json_encode($flow), // 当前采购请款单的审批流流程
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'initiator_admin_id' => $adminId->id, //
                'purchase_payroll_sn' => $purchase_payroll_sn, // 采购请款单编号
                'purchase_order_sn' => $purchase_order_sn, //
                'vin' => $vin, // 采购单编号
            ];

        if ($send_before) {
            $approve_data['approve_flow_send_before'] = json_encode($send_before);
        }
        if ($send_after) {
            $approve_data['approve_flow_send_after'] = json_encode($send_after);
        }

            $add_PurchaseEa = WaPayrollRequisitionExamineApprove::create($approve_data); // 创建的审批id
            if (!$add_PurchaseEa) {
                return '创建采购请款单审批驳回';
            }

            // 创建审批流 1供应商审批 2销售订单审批 3销售合同审批 4采购请款单审批 5采购合同审批 6采购请款审批 7交强险请款审批
//            // 采购请款单审流 创建 (创建审批流中的第一个审批)
            $approve_log_data = [
                'pr_no' => $pr_no, // 采购请款单编号
                'check_id' => $add_PurchaseEa, // 审核id
                'admin_ids' => json_encode($flow[0]->approve_admin_id), //

                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'status' => 0, //待审核 1审批通过 2 审批驳回  4  删除
                'price_name' => $param['price_name'], // 请款项目名称
                'purchase_payroll_sn' => $purchase_payroll_sn, // 采购请款单编号
            ];

            $res = WaPayrollRequisitionExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                return '创建采购请款单审批流失败';
            }
            $up_payroll = WaPurchasePayrollRequisition::updated(['status' => 1, 'pr_no' => $pr_no, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $purchase_payroll_sn]);
            if (!$up_payroll) {
                return '请款单状态修改失败';
            }
//            }
            return 'true';
        } catch (\Throwable $exception) {

            IndexController::logError('payrollApproveAddByVin', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '创建请款审批流 - 车务失败');
        }

    }


    // 创建请款审批流 - 月结
    public static function payrollApproveAddByMonth($adminId, $total_price, $param, $purchase_payroll_sn, $bill_number)
    {
//            if (round($param['total_price'], 2) < (round($param['requested_price'], 2) + round($param['this_request_price'], 2))) {
        // 本次请款金额超出总金额 需要审批

        // 订单审批类型 1供应商审批 2销售订单审批 3销售合同审批 4采购请款单审批 5采购合同审批 6采购请款审批 7交强险请款审批
        if (array_key_exists('sort', $param)) {
            if ($param['sort']) {
                $sort = $param['sort'];
            } else {
                $sort = 0;
            }
        } else {
            $sort = 0;
        }
        $flow = self::flowSttingBySort(6, $sort);
        if (!$flow) {
            return '未获取采购请款单的审批流 ';
        }

        \support\Db::beginTransaction();
        try{
            // 创建采购请款审批:
            // 创建新的采购请款单审批 -> 创建采购请款单审批流第一条待审核记录
            // 判断 采购请款单的状态 是否符合创建审核条件 是否同一笔审批未结束 采购请款单审批状态 0 审批中 1 通过 2 驳回 3作废 4删除
            $checkPurchaseApprove = WaPayrollRequisitionExamineApprove::find($adminId, ['purchase_payroll_sn' => $purchase_payroll_sn]);
            $checkPurchaseApprove = json_decode($checkPurchaseApprove);
            if ($checkPurchaseApprove) {
                if ($checkPurchaseApprove->status == 0 || $checkPurchaseApprove->status == 1) {
                    return '该订单在审核流程中不能重复创建';
                }
            }

            $pr_no = 'PR' . IndexController::getRandomNum(6);

            $approve_data = [
                'pr_no' => $pr_no, // 采购请款单编号
                'total_amount' => $total_price, // 订单金额
                'requested_price' => round($total_price, 2), //已请款金额
                'this_request_price' => round($total_price, 2), //本次请款金额
                'price_name' => $param['price_name'], // 请款项目名称
                'admin_id' => $adminId->id, // 创建人id(提交订单审批的创建人)
                'admin_name' => $adminId->nickname, // 创建人名称
                'status' => 0, // 状态 0 审批中 1 通过 2 驳回
                'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
                'approve_flow' => json_encode($flow), // 当前采购请款单的审批流流程
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'initiator_admin_id' => $adminId->id, //
                'purchase_payroll_sn' => $purchase_payroll_sn, // 采购请款单编号
                'bill_number' => $bill_number, // 采购单编号
            ];


            $add_PurchaseEa = WaPayrollRequisitionExamineApprove::create($approve_data); // 创建的审批id
            if (!$add_PurchaseEa) {
                return '创建采购请款单审批驳回';
            }

            // 创建审批流 1供应商审批 2销售订单审批 3销售合同审批 4采购请款单审批 5采购合同审批 6采购请款审批 7交强险请款审批
//            // 采购请款单审流 创建 (创建审批流中的第一个审批)
            $approve_log_data = [
                'pr_no' => $pr_no, // 采购请款单编号
                'check_id' => $add_PurchaseEa, // 审核id
                'admin_ids' => json_encode($flow[0]->approve_admin_id), //

                'created_at' => dateTime(),
                'admin_id' => $adminId->id,
                'admin_name' => $adminId->nickname,
                'initiator_admin_name' => $adminId->nickname, // 审批发起人
                'status' => 0, //待审核 1审批通过 2 审批驳回  4  删除
                'price_name' => $param['price_name'], // 请款项目名称
                'purchase_payroll_sn' => $purchase_payroll_sn, // 采购请款单编号
            ];

            $res = WaPayrollRequisitionExamineApproveFlow::create($approve_log_data);
            if (!$res) {
                return '创建采购请款单审批流失败';
            }
            $up_payroll = WaPurchasePayrollRequisition::updated(['status' => 1, 'pr_no' => $pr_no, 'updated_at' => dateTime()], ['purchase_payroll_sn' => $purchase_payroll_sn]);
            if (!$up_payroll) {
                return '请款单状态修改失败';
            }
//            }
            return 'true';
        } catch (\Throwable $exception) {

            IndexController::logError('payrollApproveAddByMonth', $param, $adminId, $exception);
            \support\Db::rollBack();
            return IndexController::errored($exception, '创建请款审批流 - 月结失败');
        }

    }

    //1
}